// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import vueResource from 'vue-resource'
import CryptoJS from 'crypto-js'
import App from './app.vue'
import router from './router'
import store from './vuex/store.js'
import '../common/fonts/iconfont.css'
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'

// import router from './router'
Vue.use(vueResource)
Vue.use(ElementUI)
Vue.config.productionTip = false
Vue.use(preview)

Vue.prototype.encrypt = function (obj) {
  var key = CryptoJS.enc.Utf8.parse('1234567812345678')
  var srcs = CryptoJS.enc.Utf8.parse(JSON.stringify(obj))
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7})
  return encrypted.toString()
}
Vue.prototype.decode = function (obj) {
  var key = CryptoJS.enc.Utf8.parse('1234567812345678')
  var decrypt = CryptoJS.AES.decrypt(obj, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7})
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}
Vue.http.interceptors.push(function (request, next) {
  request.body = this.encrypt(request.body)
  next((response) => {
    if (!response.body) return {}
    response.body = JSON.parse(this.decode(response.body))
    return response
  })
})
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    sessionStorage.removeItem('user')
  }
  let user = JSON.parse(sessionStorage.getItem('user'))
  if (!user && to.path !== '/login') {
    next({ path: '/login' })
  } else if (user && to.path === '/') {
    next({name: 'survey', params: {orignflag: 1}})
  } else {
    next()
  }
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  // router,
  store,
  router,
  template: '<App/>',
  components: { App }
})
